window.addEventListener('load', e => {
  const canvas = document.getElementById('canvas');
  const gl = getWebGLContext(canvas);
  initShaders(gl, v_shader_source, f_shader_source);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  let position = new Float32Array([
    1.0, 1.0, 1.0, 1.0, 1.0, 1.0, // v0 White
    -1.0, 1.0, 1.0, 1.0, 0.0, 1.0, // v1 Magenta
    -1.0, -1.0, 1.0, 1.0, 0.0, 0.0, // v2 Red
    1.0, -1.0, 1.0, 1.0, 1.0, 0.0, // v3 Yellow
    1.0, -1.0, -1.0, 0.0, 1.0, 0.0, // v4 Green
    1.0, 1.0, -1.0, 0.0, 1.0, 1.0, // v5 Cyan
    -1.0, 1.0, -1.0, 0.0, 0.0, 1.0, // v6 Blue
    -1.0, -1.0, -1.0, 0.0, 0.0, 0.0 // v7 Black
  ]);
  let indices = new Uint8Array([
    0, 1, 2, 0, 2, 3, // front
    0, 3, 4, 0, 4, 5, // right
    0, 5, 6, 0, 6, 1, // up
    1, 6, 7, 1, 7, 2, // left
    7, 4, 3, 7, 3, 2, // down
    4, 7, 6, 4, 6, 5 // back
  ]);
  let fSize = position.BYTES_PER_ELEMENT;

  let vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW);

  let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 6 * fSize, 0);
  gl.enableVertexAttribArray(a_Position);

  let a_Color = gl.getAttribLocation(gl.program, 'a_Color');
  gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, 6 * fSize, 3 * fSize);
  gl.enableVertexAttribArray(a_Color);

  let indexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);

  let projMatrix = new Matrix4();
  projMatrix.setPerspective(30, 1, 1, 100);
  projMatrix.lookAt(3, 3, 7, 0, 0, 0, 0, 1, 0);
  let u_ProjMatrix = gl.getUniformLocation(gl.program, 'u_ProjMatrix');
  gl.uniformMatrix4fv(u_ProjMatrix, false, projMatrix.elements);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  gl.enable(gl.DEPTH_TEST);

  gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_BYTE, 0);
});

const v_shader_source = `
  attribute vec4 a_Position;
  attribute vec4 a_Color;
  uniform mat4 u_ProjMatrix;
  varying vec4 v_Color;
  void main(){
    gl_Position = u_ProjMatrix * a_Position;
    v_Color = a_Color;
  }
`;

const f_shader_source = `
  precision lowp float;
  varying vec4 v_Color;
  void main(){
    gl_FragColor = v_Color;
  }
`;